using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Material.BOM;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.FactoryModeling;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.BOM
{
    /// <summary>
    /// 获取BOM树形结构处理器
    /// </summary>
    public class GetBOMTreeHandler : IRequestHandler<GetBOMTreeCommand, ApiResult<List<BOMTreeDTO>>>
    {
        private readonly IBaseRespository<BOMInfoModel> bomRepository;
        private readonly IBaseRespository<ProcessModel> processRepo;

        public GetBOMTreeHandler(IBaseRespository<BOMInfoModel> bomRepository, IBaseRespository<ProcessModel> processRepo)
        {
            this.bomRepository = bomRepository;
            this.processRepo = processRepo;
        }

        public Task<ApiResult<List<BOMTreeDTO>>> Handle(GetBOMTreeCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<BOMTreeDTO>>();

            try
            {
                var bom = bomRepository.GetAll().Where(x => !x.Isdel);
                var process = processRepo.GetAll().Where(x => !x.Isdel);

                // 应用筛选条件
                if (!string.IsNullOrEmpty(request.BOMName))
                {
                    bom = bom.Where(x => x.BOMName.Contains(request.BOMName));
                }

                if (!string.IsNullOrEmpty(request.BomVersion))
                {
                    bom = bom.Where(x => x.BomVersion.Contains(request.BomVersion));
                }

                if (!string.IsNullOrEmpty(request.BomType))
                {
                    bom = bom.Where(x => x.BomType.Contains(request.BomType));
                }

                if (request.ProcessId.HasValue)
                {
                    bom = bom.Where(x => x.ProcessId == request.ProcessId.Value);
                }

                // 获取所有BOM数据并关联工序信息
                var bomList = (from a in bom
                               join b in process on a.ProcessId equals b.Id
                               select new BOMTreeDTO
                               {
                                   Id = a.Id,
                                   BOMCode = a.BOMCode,
                                   BOMName = a.BOMName,
                                   BomVersion = a.BomVersion,
                                   BomType = a.BomType,
                                   BOMSteps = a.BOMSteps,
                                   BOMLevel = a.BOMLevel,
                                   ProcessId = a.ProcessId,
                                   ProcessCode = b.Processcode,
                                   ProcessName = b.Processname,
                                   BOMDosage = a.BOMDosage.HasValue ? a.BOMDosage.Value.ToString() : string.Empty,
                                   BOMDesc = a.BOMDesc,
                                   ParentBOMId = a.ParentBOMId,
                                   CreateName = a.CreateName,
                                   CreateTime = a.CreateTime,
                                   UpdateName = a.UpdateName,
                                   UpdateTime = a.UpdateTime
                               }).ToList();

                // 构建树形结构
                var tree = BuildBOMTree(bomList, request.ParentBOMId);

                result.Data = tree;
                result.Code = ApiEnum.Success;
                result.Msg = "BOM树形结构获取成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"获取BOM树形结构失败：{ex.Message}";
            }

            return Task.FromResult(result);
        }

        /// <summary>
        /// 构建BOM树形结构
        /// </summary>
        /// <param name="bomList">所有BOM数据</param>
        /// <param name="parentId">父级ID，null表示获取顶级节点</param>
        /// <returns></returns>
        private List<BOMTreeDTO> BuildBOMTree(List<BOMTreeDTO> bomList, int? parentId = null)
        {
            var result = new List<BOMTreeDTO>();

            // 获取指定父级下的直接子级
            var children = bomList.Where(x => x.ParentBOMId == parentId).ToList();

            foreach (var child in children)
            {
                // 递归获取子级的子级
                child.Children = BuildBOMTree(bomList, child.Id);
                result.Add(child);
            }

            return result;
        }
    }
}
